package com.example.springboot.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
public class Utils {

    static AtomicReference<String> messageBuffer = new AtomicReference<>(""); // 消息缓冲

    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        String preStr = "host: " + url.getHost() + "\n" + "date: " + date + "\n" + "GET " + url.getPath() + " HTTP/1.1";
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        return hostUrl + "?authorization=" + Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)) + "&date=" + date + "&host=" + url.getHost();
    }

    public static String buildChatRequestJson(String appid, String text) {
        JSONObject requestJson = new JSONObject();
        JSONObject header = new JSONObject();
        header.put("app_id", appid);
        header.put("uid", UUID.randomUUID().toString().substring(0, 10));
        JSONObject parameter = new JSONObject();
        JSONObject chat = new JSONObject();
        chat.put("domain", "lite");
        chat.put("temperature", 0.5);
        chat.put("max_tokens", 4096);
        parameter.put("chat", chat);

        JSONObject payload = new JSONObject();
        JSONObject message = new JSONObject();
        message.put("text", JSONArray.parseArray(text));
        payload.put("message", message);

        requestJson.put("header", header);
        requestJson.put("parameter", parameter);
        requestJson.put("payload", payload);

//        log.info("requestJson: {}", requestJson.toJSONString());
        return requestJson.toJSONString();
    }




    public static String parseResponse(Session session, String response) {
        try {
            // 将响应字符串解析为JSON对象
            JSONObject jsonResponse = JSON.parseObject(response);
            int status = jsonResponse.getJSONObject("header").getIntValue("status");

            List<String> dataList = new ArrayList<>();
            String mergedContent = "";

            if (status == 0) {
                // 获取payload.choices.text字段
                JSONObject payload = jsonResponse.getJSONObject("payload");
                JSONObject choices = payload.getJSONObject("choices");
                JSONArray textArray = choices.getJSONArray("text");
                // 提取第一个text对象中的content字段
                if (textArray != null && textArray.size() > 0) {
                    JSONObject textObject = textArray.getJSONObject(0);
                    // 将数据存储到列表中
                    dataList.add(textObject.getString("content"));
                }
            }
            if (status == 2) {
                for (int i = 0; i < dataList.size(); i++) {
                    mergedContent += dataList.get(i);
                }
                log.error("mergedContent :{}", mergedContent);
            }

            // 检查header中的code是否为0（表示成功）
            int code = jsonResponse.getJSONObject("header").getIntValue("code");
            if (code == 0) {
                // 获取payload.choices.text字段
                JSONObject payload = jsonResponse.getJSONObject("payload");
                JSONObject choices = payload.getJSONObject("choices");
                JSONArray textArray = choices.getJSONArray("text");

                // 提取第一个text对象中的content字段
                if (textArray != null && textArray.size() > 0) {
                    JSONObject textObject = textArray.getJSONObject(0);
                    return textObject.getString("content"); // 返回content字段的值
                }
            } else {
                // 如果返回码不是0，返回错误信息
                String errorMessage = jsonResponse.getJSONObject("header").getString("message");
                return "Error: " + errorMessage;
            }

        } catch (Exception e) {
            // 如果解析失败，返回错误信息
            return "Error: Failed to parse response";
        }
        return response;
    }

}